/**
 * Created by yuris on 27.01.15.
 */
package InterfaceObjects {
import feathers.controls.LayoutGroup;
import feathers.controls.ScrollBar;
import feathers.controls.ScrollContainer;
import feathers.display.Scale9Image;
import feathers.layout.HorizontalLayout;

import flash.geom.Point;

import flashx.textLayout.container.ScrollPolicy;

import starling.display.DisplayObject;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;

public class AbstractTabWindow extends Sprite {
    private var _bgSkin:Scale9Image;
    private var _contentSkin:Scale9Image;
    private var _windowTitle:WindowTitle;
    private var _scrollContainer:ScrollContainer;

    private var _tabsData:Array = [];
    //private var _foodContent:Vector.<OrderProductItem> = new <OrderProductItem>[];

    //private var _tabNames:Array = ["Food","Cosmetic","Electric"];
    private var _closeButton:ButtonSmall;


    public function AbstractTabWindow(title:String, tabNames:Array) {
        super();
        //this._tabNames = tabNames;
        if(tabNames.length > 0){
            for (i = 0; i < tabNames.length; i++) {
                this._tabsData.push({name:tabNames[i],items:[]});
            }
        }

        this._bgSkin = new Scale9Image(GraphicFactory.getScale9Textures("Interface/Skins/window_2"));
        this._bgSkin.alignPivot();
        this._bgSkin.useSeparateBatch = false;
        this._bgSkin.touchable = false;
        this.addChild(this._bgSkin);

        this._createTabBar();
        this._tabLayout.addEventListener(TouchEvent.TOUCH, HANDLER_tabTouch);

        this._contentSkin = new Scale9Image(GraphicFactory.getScale9Textures("Interface/Skins/window_2_content_skin"));
        this._contentSkin.alignPivot();
        this._contentSkin.useSeparateBatch = false;
        this._contentSkin.y += 20;
        this._contentSkin.touchable = false;
        this.addChild(this._contentSkin);

        this._windowTitle = new WindowTitle(title);

        addChild(this._windowTitle);

        this._scrollContainer = new ScrollContainer();
        this._scrollContainer.horizontalScrollPolicy = ScrollPolicy.OFF;
        this._scrollContainer.pageHeight = 100;
        this._scrollContainer.snapToPages = true;
        this._scrollContainer.interactionMode = ScrollContainer.INTERACTION_MODE_TOUCH_AND_SCROLL_BARS;
        this._scrollContainer.scrollBarDisplayMode = ScrollContainer.SCROLL_BAR_DISPLAY_MODE_FIXED;
        this._scrollContainer.verticalScrollBarFactory = function():ScrollBar
        {
            var scrollBar:ScrollBar = new ScrollBar();
            scrollBar.direction = ScrollBar.DIRECTION_VERTICAL;
            //skin the scroll bar here
            scrollBar.thumbProperties.defaultSkin = GraphicFactory.getImageByName("Interface/Skins/scroll_bar_vertical");
            scrollBar.trackLayoutMode = ScrollBar.TRACK_LAYOUT_MODE_SINGLE;;
            return scrollBar;
        }

        this._closeButton = new ButtonSmall(ButtonSmall.RED_TYPE,ButtonSmall.SIGN_CROSS);
        //this._closeButton.addEventListener(Event.TRIGGERED, HANDLER_closeButtonTriggered);
        this._closeButton.alignPivot();
        addChild(this._closeButton);

        this._scrollContainer.addEventListener(TouchEvent.TOUCH, HANDLER_scrollContainerTouch);

        this._alignScrollContainer();
        this._alignTab();
        this._alignCloseButton();

        addChild(this._scrollContainer);


    }

    private var _bufArray:Array;
    private var _bufTouch:Touch;
    private var _touchBeganPoint:Point = new Point();
    private var _touchEndedPoint:Point = new Point();
    public static const EVENT_CONTENT_ITEM_CLICK:String = "EVENT_CONTENT_ITEM_CLICK";
    private function HANDLER_scrollContainerTouch(event:TouchEvent):void {
        if(event.touches.length > 0){
            this._bufTouch = event.touches[0];
            if(this._bufTouch.phase == TouchPhase.BEGAN){
                this._touchBeganPoint.setTo(this._bufTouch.globalX,this._bufTouch.globalY);
                return
            } else if(this._bufTouch.phase == TouchPhase.ENDED){
                this._touchEndedPoint.setTo(this._bufTouch.globalX,this._bufTouch.globalY);
                if(Point.distance(this._touchBeganPoint,this._touchEndedPoint) >  10){
                    return;
                }
            } else {
                return
            }
            if(this._openedTabNum <= 0){
                return;
            }
            this._bufTouchTarget = this._bufTouch.target;
            this._bufArray = this._tabsData[this._openedTabNum - 1].items;
            for(i = 0; i < this._bufArray.length; i++){
                if(this._bufTouchTarget == this._bufArray[i]){
                    this.dispatchEventWith(AbstractTabWindow.EVENT_CONTENT_ITEM_CLICK, false, {item:this._bufTouchTarget});
                }
            }
        }
    }

    private function _alignCloseButton():void {
        this._closeButton.x = this._bgSkin.width/2 - 40;
        this._closeButton.y = -this._bgSkin.height/2 - 10;
    }

    private function HANDLER_closeButtonTriggered(event:Event):void {
        this.removeFromParent();
    }

    private var _bufTouchTarget:DisplayObject
    private var i:int = 0;
    private var _bufTabTouchCounter:int = 0
    private function HANDLER_tabTouch(event:TouchEvent):void {
        if(event.touches.length > 0){
            _bufTabTouchCounter ++;
            //trace("tab touch:"+_bufTabTouchCounter)
            if(event.touches[0].phase != TouchPhase.ENDED){
                return;
            }
            this._bufTouchTarget = event.touches[0].target;
            for(i = 0; i < this._tabBarButtons.length; i++){
                if(this._bufTouchTarget == this._tabBarButtons[i]){
                    this.showTab(i+1);
                } else {
                    this._tabBarButtons[i].isEnabled = true;
                }
            }
        }
    }

    private var _openedTabNum:int = 0;
    public function showTab(tabNumber:int):void {
        this._openedTabNum = tabNumber;
        this._tabBarButtons[tabNumber - 1].isEnabled = false;
        this._showTabContent(tabNumber);
    }



    private var _tabLayout:LayoutGroup = new LayoutGroup();
    private var _tabBarButtons:Vector.<ButtonLong> = new <ButtonLong>[];
    private var _buttonLongBuf:ButtonLong;
    private var _bufImage:Image;
    private function _createTabBar():void {
        this._tabLayout.layout = new HorizontalLayout();
        (this._tabLayout.layout as HorizontalLayout).gap = 0

        for ( i = 0; i < this._tabsData.length; i++) {
            this._buttonLongBuf = new ButtonLong(ButtonLong.ORANGE_TYPE);
            this._buttonLongBuf.label = this._tabsData[i].name;
            this._buttonLongBuf.labelOffsetY -= 5;
            this._bufImage = GraphicFactory.getImageByName("Interface/Buttons/button_1_long_green");
            this._bufImage.alignPivot("left","top");
            this._buttonLongBuf.disabledSkin = this._bufImage;
            _tabBarButtons.push(_buttonLongBuf);
            _tabLayout.addChild(_buttonLongBuf);

        }
        addChild(this._tabLayout);
    }


    public function addTabContentMultiData(tabNum:uint,content:Array):void {
        for (var i:int = 0; i < content.length; i++) {
            this._tabsData[tabNum - 1].items.push(this._contentItemFactory(content[i]));
        }
    }
    public function addTabContentSingleData(tabNum:uint,data:Object):void {
        this._tabsData[tabNum - 1].items.push(this._contentItemFactory(data));
    }

    virtual protected function _contentItemFactory(itemData:Object):Sprite {
        throw new Error("AbstractTabWindow.as: function contentItemFactory() is not defined");
        return null;
    }

    private function _showTabContent(tabNum:uint):void {
        this._scrollContainer.removeChildren();
        this._showItems(this._tabsData[tabNum - 1].items);
    }

    private var _bufPoint:Point =  new Point();
    protected function _itemPositionFactory(itemNum:int):Point {
        this._bufPoint.setTo(2 +(itemNum % 2)* 260 - 80*0,int(itemNum*0.5) * 100)
        return this._bufPoint;
    }
    private function _showItems(items:Array):void {
        for (var i:int = 0; i < items.length; i++) {
            _bufPoint = this._itemPositionFactory(i);
            items[i].x = this._bufPoint.x;
            items[i].y = this._bufPoint.y;
            this._scrollContainer.addChild(items[i] as Sprite);
        }
    }

    private function _alignScrollContainer():void {
        this._scrollContainer.width = this._contentSkin.width - 12;
        this._scrollContainer.height = this._contentSkin.height - 8;
        this._scrollContainer.x = this._contentSkin.x;
        this._scrollContainer.y = this._contentSkin.y;
        this._scrollContainer.alignPivot();
    }
    private function _alignTab():void {
        this._tabLayout.x = this._contentSkin.x - this._contentSkin.width/2 + 4;
        this._tabLayout.y = this._contentSkin.y - this._contentSkin.height/2 - 30;;
    }

    override public function set width(value:Number):void {
        this._bgSkin.width = value;
        this._contentSkin.width = value * 0.9;
        this._bgSkin.alignPivot();
        this._contentSkin.alignPivot();
        this._windowTitle.x = - this._windowTitle.width/2;

        this._alignScrollContainer();
        this._alignTab();
        this._alignCloseButton();

    }

    override public function set height(value:Number):void {
        this._bgSkin.height = value;
        this._contentSkin.height = value * 0.9 - 80;
        this._bgSkin.alignPivot();
        this._contentSkin.alignPivot();
        this._windowTitle.y = - this._bgSkin.height/2 - 10;

        this._alignScrollContainer();
        this._alignTab();
        this._alignCloseButton();


    }

    public function get currentTabNum():int {
        return _openedTabNum;
    }

    public function get closeButton():ButtonSmall {
        return _closeButton;
    }

    public function get scrollContainer():ScrollContainer {
        return _scrollContainer;
    }
}
}
